package com.xmtlxx.web.controller.oms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmtlxx.common.constant.Constants;
import com.xmtlxx.common.core.domain.PageQuery;
import com.xmtlxx.common.core.domain.entity.SysDictData;
import com.xmtlxx.common.core.page.TableDataInfo;
import com.xmtlxx.common.enums.PropertyLogType;
import com.xmtlxx.common.exception.ServiceException;
import com.xmtlxx.common.helper.LoginHelper;
import com.xmtlxx.common.sms.aliyun.AliyunSmsService;
import com.xmtlxx.common.sms.aliyun.SmsRequest;
import com.xmtlxx.common.sms.aliyun.SmsTemplateCode;
import com.xmtlxx.common.sms.aliyun.SmsTemplateParam;
import com.xmtlxx.common.utils.DateUtils;
import com.xmtlxx.common.utils.JsonUtils;
import com.xmtlxx.common.utils.StringUtils;
import com.xmtlxx.oms.domain.Property;
import com.xmtlxx.oms.domain.TaskDisposalInfo;
import com.xmtlxx.oms.domain.TaskDtl;
import com.xmtlxx.oms.domain.bo.*;
import com.xmtlxx.oms.domain.vo.*;
import com.xmtlxx.oms.mapper.*;
import com.xmtlxx.system.domain.SysOss;
import com.xmtlxx.system.domain.bo.SysOssBo;
import com.xmtlxx.system.enums.OssBuss;
import com.xmtlxx.system.mapper.SysDeptMapper;
import com.xmtlxx.system.mapper.SysDictDataMapper;
import com.xmtlxx.system.mapper.SysOssMapper;
import com.xmtlxx.system.service.ISysConfigService;
import com.xmtlxx.web.controller.center.service.ICenterService;
import com.xmtlxx.web.controller.center.service.ICommonService;
import com.xmtlxx.web.controller.center.vo.SendTaskVo;
import com.xmtlxx.web.controller.oms.service.IDisposalTaskService;
import com.xmtlxx.web.controller.oms.service.ITaskService;
import com.xmtlxx.web.controller.wms.service.IExWarehouseService;
import com.xmtlxx.web.controller.wms.service.IHandoverService;
import com.xmtlxx.wms.domain.bo.ExWarehouseBo;
import com.xmtlxx.wms.domain.bo.HandoverBo;
import com.xmtlxx.wms.domain.bo.StoreBo;
import com.xmtlxx.wms.domain.vo.ExWarehouseDtlVo;
import com.xmtlxx.wms.domain.vo.ExWarehouseVo;
import com.xmtlxx.wms.domain.vo.StoreVo;
import com.xmtlxx.wms.mapper.StoreMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Service
public class DisposalTaskServiceImpl implements IDisposalTaskService {

    private final TaskMapper baseMapper;

    private final TaskDtlMapper taskDtlMapper;

    private final ContactsMapper contactsMapper;

    private final SysDictDataMapper dictDataMapper;

    private final StoreMapper storeMapper;

    private final ICommonService commonService;

    private final SysOssMapper sysOssMapper;

    private final ISysConfigService configService;

    private final ITaskService taskService;

    private final IHandoverService handoverService;

    private final IExWarehouseService exWarehouseService;

    private final SysDeptMapper deptMapper;

    private final TaskDisposalInfoMapper taskDisposalInfoMapper;

    private final PropertyMapper propertyMapper;

    private final ICenterService centerService;

    private final AliyunSmsService aliyunSmsService;

    @Override
    public TaskVo initBean(TaskVo taskVo) {

        TaskVo vo = new TaskVo();
        List<TaskDtlVo> items = new ArrayList<>();
        if (StringUtils.isNotEmpty(taskVo.getId())) {
            vo = taskService.queryById(taskVo.getId());
            TaskDtlBo dtlBo = new TaskDtlBo();
            dtlBo.setTaskId(vo.getId());
            items = taskDtlMapper.selectTaskDtlList(dtlBo);
            if (items != null && items.size() > 0) {
                for (TaskDtlVo dtlVo : items) {
                    SysOssBo ossBo = new SysOssBo();
                    ossBo.setObjid(dtlVo.getPno());
                    dtlVo.setOss(sysOssMapper.selectOssList(ossBo));
                }
            }
            TaskDisposalInfo disposalInfo = taskDisposalInfoMapper.getDisposalInfo(vo.getId());
            if (!StringUtils.isEmpty(vo.getIsTrailer()) && vo.getIsTrailer().equals("1")) {
                SysOssBo ossBo = new SysOssBo();
                ossBo.setObjid(vo.getId());
                switch (vo.getDealType()) {
                    case "3":
                        vo.setPolice(disposalInfo.getPolice());
                        vo.setPoliceTel(disposalInfo.getPoliceTel());
                        vo.setBacker(disposalInfo.getPerson());
                        vo.setBackCard(disposalInfo.getPersonCertNo());
                        vo.setIsDepute(disposalInfo.getIsEntrust());
                        if (StringUtils.isNotBlank(disposalInfo.getIsEntrust()) && disposalInfo.getIsEntrust().equals("1")) {
                            vo.setRelation(disposalInfo.getEntrustRelation());
                        } else {
                            vo.setIsDepute("0");
                        }

                        ossBo.setBuss(OssBuss.DISPOSAL_APPLY_LIST.getValue());
                        List<SysOss> backOss = sysOssMapper.selectSysOssList(ossBo);
                        if (backOss != null) {
                            vo.setBackOss(backOss);
                        } else {
                            vo.setBackOss(new ArrayList<>());
                        }

                        ossBo.setBuss(OssBuss.DISPOSAL_APPLY_CERT.getValue());
                        List<SysOss> repayOss = sysOssMapper.selectSysOssList(ossBo);
                        if (repayOss != null) {
                            vo.setRepayOss(repayOss);
                        } else {
                            vo.setRepayOss(new ArrayList<>());
                        }

                        ossBo.setBuss(OssBuss.DISPOSAL_APPLY_AUTHORIZE.getValue());
                        List<SysOss> authorizeOss = sysOssMapper.selectSysOssList(ossBo);
                        if (authorizeOss != null) {
                            vo.setAuthorizeOss(authorizeOss);
                        } else {
                            vo.setAuthorizeOss(new ArrayList<>());
                        }

                        break;
                    case "5":

                        vo.setPolice(disposalInfo.getPolice());
                        vo.setPoliceTel(disposalInfo.getPoliceTel());
                        ossBo.setBuss(OssBuss.DISPOSAL_APPLY_AUTHORIZE.getValue());
                        List<SysOss> saleOss = sysOssMapper.selectSysOssList(ossBo);
                        if (saleOss != null) {
                            vo.setSaleOss(saleOss);
                        } else {
                            vo.setSaleOss(new ArrayList<>());
                        }
                        break;
                    case "6":
                        ossBo.setBuss(OssBuss.DISPOSAL_APPLY_AUTHORIZE.getValue());
                        List<SysOss> ruinOss = sysOssMapper.selectSysOssList(ossBo);
                        if (ruinOss != null) {
                            vo.setRuinOss(ruinOss);
                        } else {
                            vo.setRuinOss(new ArrayList<>());
                        }
                        break;
                    default:
                        break;
                }

                SysOssBo bussBo = new SysOssBo();
                bussBo.setObjid(vo.getId());
                ossBo.setBuss("dealsForm");
                List<SysOss> dealsOss = sysOssMapper.selectSysOssList(bussBo);
                if (dealsOss != null && dealsOss.size() > 0) {
                    vo.setDealsOss(dealsOss);
                } else {
                    vo.setDealsOss(new ArrayList<>());
                }
            } else {
                if (vo.getDelivery().equals("1")) {
                    vo.setPickuper(disposalInfo.getPerson());
                    vo.setPickupTel(disposalInfo.getPersonTel());
                    vo.setPickupCardType(disposalInfo.getCertType());
                    vo.setPickupCard(disposalInfo.getPersonCertNo());
                }
            }

        } else {
            vo.setDelivery("0");//物流配送默认为0
            vo.setDeptId(LoginHelper.getDeptId());
            vo.setDeptName(LoginHelper.getLoginUser().getDeptName());
            vo.setSource("0");

            ContactsVo contactsVo = null;
            ContactsBo contactsBo = new ContactsBo();
            contactsBo.setDeptId(LoginHelper.getDeptId());
            List<ContactsVo> contactsVos = contactsMapper.selectContactsList(contactsBo);
            //获取联系人信息
            if (contactsVos != null && contactsVos.size() > 0) {
                for (ContactsVo contacts : contactsVos) {
                    if (!StringUtils.isEmpty(contacts.getFlag()) && contacts.getFlag().equals("Y")) {
                        contactsVo = contacts;
                        break;
                    }
                }
                if (ObjectUtil.isNull(contactsVo)) {
                    contactsVo = contactsVos.get(0);
                }
            }
            if (ObjectUtil.isNotNull(contactsVo)) {
                vo.setName(contactsVo.getName());
                vo.setTel(contactsVo.getTel());
                vo.setAddress(contactsVo.getAddress());
            }
            vo.setIsTrailer("1");
            vo.setIsDepute("0");
            vo.setBackOss(new ArrayList<>());
            vo.setRepayOss(new ArrayList<>());
            vo.setAuthorizeOss(new ArrayList<>());
            vo.setRuinOss(new ArrayList<>());
            vo.setSaleOss(new ArrayList<>());
        }

        List<StoreVo> storeVoList = storeMapper.selectStoreList(new StoreBo());
        List<SysDictData> dictDataList = dictDataMapper.selectDictDataByType("oms_property_type");
        List<StoreDictVo> dictList = dictDataList.stream().map(dict -> {
            StoreDictVo dictVo = new StoreDictVo();
            dictVo.setLabel(dict.getDictLabel());
            dictVo.setValue(dict.getDictValue());
            switch (dict.getDictValue()) {
                case "3":
                    dictVo.setStoreId(storeVoList.get(1).getId());
                    dictVo.setName(storeVoList.get(1).getName());
                    break;
                default:
                    dictVo.setStoreId(storeVoList.get(0).getId());
                    dictVo.setName(storeVoList.get(0).getName());
                    break;
            }
            return dictVo;
        }).collect(Collectors.toList());
        vo.setDictList(dictList);
        vo.setItems(items);
        vo.setType(taskVo.getType());
        return vo;
    }
//
//    @Override
//    public TaskVo queryById(String id) {
//
//        TaskVo vo = baseMapper.selectTaskVoByID(id);
//        TaskDtlBo dtlBo = new TaskDtlBo();
//        dtlBo.setTaskId(id);
//        dtlBo.setDelFlag("0");
//        List<TaskDtlVo> dtls = taskDtlMapper.selectTaskDtlList(dtlBo);
//        vo.setItems(dtls);
//
//        SysOssBo oss = new SysOssBo();
//        oss.setObjid(vo.getId());
//        oss.setBuss("deal_register");
//        List<SysOss> ossList = sysOssMapper.selectSysOssList(oss);
//        if (ossList != null && ossList.size() > 0) {
//            vo.setOss(ossList);
//        } else {
//            vo.setOss(new ArrayList<>());
//        }
//
//        if (vo.getStatus().equals("1")) {
//            vo.setIsUpdate(true);
//        }
//
//        return vo;
//    }
//
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public TaskVo insertByBo(TaskBo bo) {
//
//        TaskVo vo = new TaskVo();
//        Task add = BeanUtil.toBean(bo, Task.class);
//        validEntityBeforeSave(add);
//
//        /**
//         * 默认配置
//         */
//        add.setId(IdUtil.simpleUUID());
//        add.setStatus("0");
//        add.setDelFlag("0");
//        add.setTaskNo(getNo("C"));//设置编号
//
//        /**
//         * 下发状态
//         */
//        add.setSendStatus("0");
//        add.setSendReStatus("0");
//
//        /**
//         * 默认已审核
//         */
//        add.setCheckStatus("1");
//
//        if (TaskConstant.DELIVERY.equals(add.getDelivery())
//                ||
//                (!StringUtils.isEmpty(add.getIsTrailer()) && add.getIsTrailer().equals("1"))) {
//            add.setCheckStatus("0");
//        }
//        /**
//         * 登记状态
//         */
//        add.setIsRegister("0");
//
//        /**
//         * buss 类型
//         * 0-物品 1-车辆
//         */
//        StoreVo storeVo = storeMapper.selectVoById(add.getStoreId());
//        if (storeVo != null) {
//            if (storeVo.getName().equals("车辆仓")) {
//                add.setBuss("1");
//            } else {
//                add.setBuss("0");
//            }
//        }
//
//        List<TaskDtl> dtls = new ArrayList<>();
//        if (bo.getItems() != null && bo.getItems().size() > 0) {
//            dtls = bo.getItems().stream().map(item -> {
//                TaskDtl dtl = BeanUtil.toBean(item, TaskDtl.class);
//                dtl.setId(IdUtil.simpleUUID());
//                dtl.setTaskId(add.getId());
//                dtl.setDelFlag("0");
//                dtl.setStatus("0");
//
//                if (StringUtils.isNotEmpty(add.getDealType())) {
//                    dtl.setDealType(add.getDealType());
//                }
//
//                String info = JsonUtils.toJsonString(dtl);
//                String logContent = PropertyLogType.DISPOSAL_TASK.getInfo() + "：(物品编号：" + item.getPno() + "，物品名称：" + item.getName() + "，申请说明：" + (StringUtils.isNotEmpty(add.getRemark()) ? add.getRemark() : "") + ")";
//                commonService.savePropertyLog(dtl.getPno(), add.getId(), dtl.getName(), PropertyLogType.DISPOSAL_TASK.getCode(), logContent, dtl.getDeptId(), info, add.getStoreId(), dtl.getNums(), null);
//
//                return dtl;
//            }).collect(Collectors.toList());
//
//        }
//
//        /**
//         * 授权管理中心
//         */
//        if (add.getIsTrailer().equals("1")) {
//            switch (add.getDealType()) {
//                case "3"://返还当事人
//                    /**
//                     * 领取人证件附件
//                     */
//                    TaskBo info = new TaskBo();
//                    info.setPolice(bo.getPolice());
//                    info.setPoliceTel(bo.getPoliceTel());
//                    info.setBacker(bo.getBacker());
//                    info.setBackTel(bo.getBackTel());
//                    info.setBackCard(bo.getBackCard());
//                    info.setIsDepute(bo.getIsDepute());
//                    if (bo.getIsDepute().equals("1")) {
//                        info.setRelation(bo.getRelation());
//                    }
//
//                    /**
//                     * 领取人证件附件
//                     */
//                    if (bo.getBackOss() != null && bo.getBackOss().size() > 0) {
//                        for (SysOss oss : bo.getBackOss()) {
//                            oss.setObjid(add.getId());
//                            oss.setBuss("backDeal");
//                            sysOssMapper.updateById(oss);
//                        }
//                    }
//                    /**
//                     * 发还清单附件
//                     */
//                    if (bo.getRepayOss() != null && bo.getRepayOss().size() > 0) {
//                        for (SysOss oss : bo.getRepayOss()) {
//                            oss.setObjid(add.getId());
//                            oss.setBuss("repayDeal");
//                            sysOssMapper.updateById(oss);
//                        }
//                    }
//                    /**
//                     * 委托授权书附件
//                     */
//                    if (bo.getAuthorizeOss() != null && bo.getAuthorizeOss().size() > 0) {
//                        for (SysOss oss : bo.getAuthorizeOss()) {
//                            oss.setObjid(add.getId());
//                            oss.setBuss("authorizeDeal");
//                            sysOssMapper.updateById(oss);
//                        }
//                    }
//                    add.setInfo(JsonUtils.toJsonString(info));
//                    break;
//                case "5"://拍卖
//                    /**
//                     * 拍卖清单附件
//                     */
//
//                    TaskBo saleInfo = new TaskBo();
//                    saleInfo.setPolice(bo.getPolice());
//                    saleInfo.setPoliceTel(bo.getPoliceTel());
//
//                    if (bo.getSaleOss() != null && bo.getSaleOss().size() > 0) {
//                        for (SysOss oss : bo.getSaleOss()) {
//                            oss.setObjid(add.getId());
//                            oss.setBuss("saleDeal");
//                            sysOssMapper.updateById(oss);
//                        }
//                    }
//                    add.setInfo(JsonUtils.toJsonString(saleInfo));
//                    break;
//                case "6"://销毁
//                    /**
//                     * 销毁清单附件
//                     */
//                    if (bo.getRuinOss() != null && bo.getRuinOss().size() > 0) {
//                        for (SysOss oss : bo.getRuinOss()) {
//                            oss.setObjid(add.getId());
//                            oss.setBuss("ruinDeal");
//                            sysOssMapper.updateById(oss);
//                        }
//                    }
//                    break;
//            }
//        } else {
//            if (bo.getDelivery().equals("1")) {
//                TaskBo info = new TaskBo();
//                info.setPickuper(bo.getPickuper());
//                info.setPickupTel(bo.getPickupTel());
//                info.setPickupCardType(bo.getPickupCardType());
//                info.setPickupCard(bo.getPickupCard());
//                add.setInfo(JsonUtils.toJsonString(info));
//            }
//        }
//
//        Long nums = 0L;
//        if (dtls.size() > 0) {
//            taskDtlMapper.insertBatch(dtls);
//            nums = dtls.stream().mapToLong(item -> item.getNums()).sum();
//        }
//        add.setNums(nums);//设置物品总数
//
//        /**
//         * 附件
//         */
//        if (bo.getOss() != null && bo.getOss().size() > 0) {
//            bo.getOss().stream().forEach(oss -> {
//                oss.setBuss("oms_deal");
//                oss.setObjid(add.getId());
//                sysOssMapper.updateById(oss);
//            });
//        }
//
//        boolean flag = baseMapper.insert(add) > 0;
//
//        List<OperatorLog> oplogs = new ArrayList<>();
//        if (flag) {
//            BeanUtil.copyProperties(add, vo);
//            oplogs.add(commonService.saveOperatorLog(add.getId(), "oms", PropertyLogType.DISPOSAL_TASK.getInfo()));//操作日志
//
//            /**
//             * 新订单提醒
//             */
//            if (storeVo != null) {
//                String phone = configService.selectConfigByKey("app.oms.dispatch.phone");
//                SmsRequest smsRequest = new SmsRequest();
//                if (bo.getType().equals("2")) {
//                    smsRequest.setTemplateCode(SmsTemplateCode.DISPOSAL_NOTICE.getSMS_CODE());
//                    smsRequest.setPhoneNumber(phone);
//                    SmsTemplateParam templateParam = new SmsTemplateParam();
//                    smsRequest.setTemplateParam(templateParam);
//                    AliyunSmsUtils.AliyunSmsSend(smsRequest);
//
//                    String dealPhone = configService.selectConfigByKey("app.oms.deal.phone");
//                    if (!StringUtils.isEmpty(dealPhone)) {
//                        smsRequest.setPhoneNumber(dealPhone);
//                        AliyunSmsUtils.AliyunSmsSend(smsRequest);
//                    }
//                } else {
//                    /**
//                     * 调度员
//                     */
//                    if (add.getDelivery().equals("0") && add.getType().equals("0")) {
//                        SmsRequest dSmsRequest = new SmsRequest();
//                        if (StringUtils.isNotBlank(phone)) {
//                            dSmsRequest.setTemplateCode(SmsTemplateCode.TASK_NOTICE.getSMS_CODE());
//                            dSmsRequest.setPhoneNumber(phone);
//                            SmsTemplateParam dTemplateParam = new SmsTemplateParam();
//                            dTemplateParam.setOrderType("处置");
//                            dSmsRequest.setTemplateParam(dTemplateParam);
//                            AliyunSmsUtils.AliyunSmsSend(dSmsRequest);
//                        }
//                    }
//                }
//
//            }
//        }
//
//        if (bo.getDealIds() != null && bo.getDealIds().size() > 0) {
//            Deal updateEnty = new Deal();
//            updateEnty.setIsAck("1");
//            updateEnty.setAcker(LoginHelper.getNickname());
//            updateEnty.setAckTime(new Date());
//            updateEnty.setTaskId(add.getId());
//            dealMapper.update(updateEnty, new LambdaQueryWrapper<Deal>().in(Deal::getId, bo.getDealIds()));
//        }
//
//        return vo;
//    }
//
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public TaskVo updateByBo(TaskBo bo) {
//
//        TaskVo vo = new TaskVo();
//        com.xmtlxx.oms.domain.Task update = BeanUtil.toBean(bo, com.xmtlxx.oms.domain.Task.class);
//        validEntityBeforeSave(update);
//        Long nums = update.getNums();
//
//        /**
//         * 已下发申请单，重新下发
//         * sendStatus 下发状态 0-待下发 1-已下发
//         * sendReStatus 重新下发状态 0-待下发 1-已下发
//         */
//        if (update.getSendStatus().equals("1")) {
//            update.setSendReStatus("0");
//        }
//        TaskDtlBo dtlBo = new TaskDtlBo();
//        dtlBo.setTaskId(update.getId());
//        List<TaskDtlVo> olds = taskDtlMapper.selectTaskDtlList(dtlBo);
//        List<TaskDtl> dtls = new ArrayList<>();
//        if (bo.getItems() != null && bo.getItems().size() > 0) {
//            dtls = bo.getItems().stream().map(item -> {
//                TaskDtl dtl = BeanUtil.toBean(item, TaskDtl.class);
//                if (StringUtils.isBlank(dtl.getId())) {
//                    dtl.setId(IdUtil.simpleUUID());
//                    dtl.setDelFlag("0");
//                    dtl.setStatus("0");
//                    dtl.setTaskId(update.getId());
//                    if (StringUtils.isNotEmpty(update.getDealType())) {
//                        dtl.setDealType(update.getDealType());
//                    }
//                }
//
//                /**
//                 * 迭代查询移除的明细
//                 */
//                Iterator iterator = olds.iterator();
//                while (iterator.hasNext()) {
//                    TaskDtlVo taskDtl = (TaskDtlVo) iterator.next();
//                    if (taskDtl.getId().equals(dtl.getId())) {
//                        iterator.remove();
//                    }
//                }
//                return dtl;
//            }).collect(Collectors.toList());
//        }
//
//        /**
//         * 授权管理中心
//         */
//        if (update.getIsTrailer().equals("1")) {
//            switch (update.getDealType()) {
//                case "3"://返还当事人
//                    /**
//                     * 领取人证件附件
//                     */
//                    TaskBo info = new TaskBo();
//                    info.setPolice(bo.getPolice());
//                    info.setPoliceTel(bo.getPoliceTel());
//                    info.setBacker(bo.getBacker());
//                    info.setBackTel(bo.getBackTel());
//                    info.setBackCard(bo.getBackCard());
//                    info.setIsDepute(bo.getIsDepute());
//                    if (bo.getIsDepute().equals("1")) {
//                        info.setRelation(bo.getRelation());
//                    }
//
//                    /**
//                     * 领取人证件附件
//                     */
//                    if (bo.getBackOss() != null && bo.getBackOss().size() > 0) {
//                        for (SysOss oss : bo.getBackOss()) {
//                            oss.setObjid(update.getId());
//                            oss.setBuss("backDeal");
//                            sysOssMapper.updateById(oss);
//                        }
//                    }
//                    /**
//                     * 发还清单附件
//                     */
//                    if (bo.getRepayOss() != null && bo.getRepayOss().size() > 0) {
//                        for (SysOss oss : bo.getRepayOss()) {
//                            oss.setObjid(update.getId());
//                            oss.setBuss("repayDeal");
//                            sysOssMapper.updateById(oss);
//                        }
//                    }
//                    /**
//                     * 委托授权书附件
//                     */
//                    if (bo.getAuthorizeOss() != null && bo.getAuthorizeOss().size() > 0) {
//                        for (SysOss oss : bo.getAuthorizeOss()) {
//                            oss.setObjid(update.getId());
//                            oss.setBuss("authorizeDeal");
//                            sysOssMapper.updateById(oss);
//                        }
//                    }
//                    update.setInfo(JsonUtils.toJsonString(info));
//                    break;
//                case "5"://拍卖
//                    /**
//                     * 拍卖清单附件
//                     */
//
//                    TaskBo saleInfo = new TaskBo();
//                    saleInfo.setPolice(bo.getPolice());
//                    saleInfo.setPoliceTel(bo.getPoliceTel());
//
//                    if (bo.getSaleOss() != null && bo.getSaleOss().size() > 0) {
//                        for (SysOss oss : bo.getSaleOss()) {
//                            oss.setObjid(update.getId());
//                            oss.setBuss("saleDeal");
//                            sysOssMapper.updateById(oss);
//                        }
//                    }
//                    update.setInfo(JsonUtils.toJsonString(saleInfo));
//                    break;
//                case "6"://销毁
//                    /**
//                     * 销毁清单附件
//                     */
//                    if (bo.getRuinOss() != null && bo.getRuinOss().size() > 0) {
//                        for (SysOss oss : bo.getRuinOss()) {
//                            oss.setObjid(update.getId());
//                            oss.setBuss("ruinDeal");
//                            sysOssMapper.updateById(oss);
//                        }
//                    }
//                    break;
//            }
//        } else {
//            if (bo.getDelivery().equals("1")) {
//                TaskBo info = new TaskBo();
//                info.setPickuper(bo.getPickuper());
//                info.setPickupTel(bo.getPickupTel());
//                info.setPickupCardType(bo.getPickupCardType());
//                info.setPickupCard(bo.getPickupCard());
//                update.setInfo(JsonUtils.toJsonString(info));
//            }
//        }
//
//        if (dtls.size() > 0) {
//            taskDtlMapper.insertOrUpdateBatch(dtls);
//            nums = dtls.stream().mapToLong(item -> item.getNums()).sum();
//        }
//        update.setNums(nums);//设置物品总数
//
//        /**
//         * 附件
//         */
//        if (bo.getOss() != null && bo.getOss().size() > 0) {
//            bo.getOss().stream().forEach(oss -> {
//                oss.setBuss("oms_deal");
//                oss.setObjid(update.getId());
//                sysOssMapper.updateById(oss);
//            });
//        }
//
//        //已删除的物品处理：删除dtl表、回退可移交状态
//        if (olds != null && olds.size() > 0) {
//            olds.forEach(item -> {
//                taskDtlMapper.deleteByDtlId(item.getId());
//            });
//        }
//
//        boolean flag = baseMapper.updateById(update) > 0;
//
//        List<OperatorLog> oplogs = new ArrayList<>();
//        if (flag) {
//            BeanUtil.copyProperties(update, vo);
//            oplogs.add(commonService.saveOperatorLog(update.getId(), "oms", "修改处置申请"));
//        }
//        return vo;
//    }
//
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public Boolean register(TaskBo bo) {
//
//        com.xmtlxx.oms.domain.Task update = BeanUtil.toBean(bo, com.xmtlxx.oms.domain.Task.class);
//        validEntityBeforeSave(update);
//        update.setIsRegister("1");
//        if (bo.getItems() != null && bo.getItems().size() > 0) {
//            List<Deal> dealList = bo.getItems().stream().map(item -> {
//                Deal deal = dealMapper.selectDealVoByNo(item.getPno(), update.getId());
//                return deal;
//            }).collect(Collectors.toList());
//
//            dealList.stream().forEach(deal -> {
//                deal.setRegistrant(LoginHelper.getNickname());
//                deal.setRegisterTime(new Date());
//                JSONObject registerInfo = JSONObject.parseObject(bo.getRegisterInfo());
//                registerInfo.put("disposalNumber", deal.getNums());
//                deal.setRegisterInfo(JSONObject.toJSONString(registerInfo));
//                deal.setIsRegister("1");
//                BigDecimal dealMoney = BigDecimal.ZERO;
//                if (registerInfo.get("dealPrice") != null && !StringUtils.isEmpty(registerInfo.get("dealPrice").toString())) {
//                    dealMoney = BigDecimal.valueOf(Double.valueOf(registerInfo.get("dealPrice").toString()));
//                }
//                deal.setDealMoney(dealMoney);
//                dealMapper.updateById(deal);
//            });
//        }
//
//        return baseMapper.updateById(update) > 0;
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sendTask(SendTaskVo vo) {

        if (vo.getIds() == null || vo.getIds().length == 0) {
            throw new ServiceException("参数异常，请联系管理员！");
        }

        //忽略参数
        String[] ignoreProperties = {"id", "createBy", "createTime", "updateBy", "updateTime"};

        for (String id : vo.getIds()) {
            TaskVo taskVo = taskService.queryById(id);
            TaskBo taskBo = BeanUtil.toBean(taskVo, TaskBo.class);
            com.xmtlxx.oms.domain.Task update = BeanUtil.toBean(taskBo, com.xmtlxx.oms.domain.Task.class);

            StoreVo store = storeMapper.selectStoreVoByID(taskBo.getStoreId());

            TaskDtlBo dtlBo = new TaskDtlBo();
            dtlBo.setTaskId(id);
            dtlBo.setDelFlag("0");
            List<TaskDtlVo> dtls = taskDtlMapper.selectTaskDtlList(dtlBo);

//            DealBo dealQuery = new DealBo();
//            dealQuery.setTaskId(update.getId());
//            List<DealVo> dealOlds = dealMapper.selectDealList(dealQuery);
//
//            dtls.stream().forEach(item -> {
//                Deal deal = dealMapper.selectDealVoByNo(item.getPno(), update.getId());
//                if (deal == null) {
//                    deal = new Deal();
//                    deal.setId(IdUtil.simpleUUID());
//                    deal.setStatus("0");
//                    deal.setDelFlag("0");
//                    deal.setSource("0");
//                    deal.setIsAck("0");
//                    deal.setIsFinish("0");
//                    deal.setTaskId(taskBo.getId());
//                    deal.setNums(item.getNums());
//                    deal.setDealNo(item.getPno());
//                    deal.setDealType(item.getDealType());
//                    deal.setStoreId(item.getStoreId());
//                    deal.setDeptId(item.getDeptId());
//                    deal.setIsCheck("1");
//
//                    String isSign = "0";
//
//                    if (taskBo.getIsTrailer().equals("1")) {
//                        isSign = "1";
//                    }
//
//
//                    deal.setIsSign(isSign);
//
//                    boolean flag = dealMapper.insert(deal) > 0;
//                    if (flag) {
//                        DealDtl dealDtl = BeanUtil.toBean(item, DealDtl.class);
//                        dealDtl.setId(IdUtil.simpleUUID());
//                        dealDtl.setDealId(deal.getId());
//                        dealDtl.setDelFlag("0");
//                        dealDtl.setStatus("0");
//
//                        InventoryVo inventory = inventoryMapper.selectInventoryVoByPno(item.getPno());
//                        dealDtl.setStoreId(inventory.getStoreId());
//                        dealDtl.setAreaId(inventory.getAreaId());
//                        dealDtl.setLocatorId(inventory.getLocatorId());
//                        dealDtlMapper.insert(dealDtl);
//                    }
//                } else {
//
//
//                    Iterator dIterator = dealOlds.iterator();
//                    while (dIterator.hasNext()) {
//                        DealVo deals = (DealVo) dIterator.next();
//                        if (deals.getDealNo().equals(item.getPno())) {
//                            dIterator.remove();
//                        }
//                    }
//
//                    deal.setNums(item.getNums());
//                    deal.setIsCheck("1");
//                    deal.setDelFlag("0");
//                    boolean flag = dealMapper.updateById(deal) > 0;
//                    if (flag) {
//                        DealDtl dealDtl = dealDtlMapper.selectOne(new LambdaQueryWrapper<DealDtl>().eq(DealDtl::getDealId, deal.getId()));
//                        dealDtl.setNums(item.getNums());
//                        dealDtlMapper.updateById(dealDtl);
//                    }
//                }
//
//            });
//
//            if (dealOlds != null && dealOlds.size() > 0) {
//                dealOlds.forEach(item -> {
//                    dealMapper.deleteWithDealDtlById(item.getId());
//                });
//            }

            /**
             * 下发状态
             */
            update.setSendStatus("1");
            update.setSendReStatus("1");
            baseMapper.updateTask(update);

            /**
             * 是否授权管理中心
             * 0-未授权 1-授权
             */

            if (taskBo.getIsTrailer().equals("0")) {
                centerService.sendsTask(vo);
            } else {

                /**
                 * 处置单生成-出库单生成
                 */
                ExWarehouseVo dealVo = exWarehouseService.queryByTaskId(id);
                ExWarehouseBo dealBo = new ExWarehouseBo();
                dealBo.setDelFlag("0");
                List<ExWarehouseDtlVo> ddtls = dtls.stream().map(item -> {
                    ExWarehouseDtlVo ddtl = new ExWarehouseDtlVo();
                    BeanUtil.copyProperties(item, ddtl, "id");
                    return ddtl;
                }).collect(Collectors.toList());

                if (ObjectUtil.isNull(dealVo)) {
                    BeanUtil.copyProperties(taskBo, dealBo, ignoreProperties);
                    dealBo.setExno(taskBo.getTaskNo());
                    dealBo.setTaskId(taskBo.getId());
                    dealBo.setFlag(taskBo.getDelivery());
                    dealBo.setIsFinish("0");//是否上架结束 0-待挑拣 1-已挑拣
                    dealBo.setIsValidate("0");//是否需要确认 0-无需确认 1-需确认
                    dealBo.setIsSign("0");//是否已签收 0-待签收 1-已签收
                    dealBo.setStoreId(store.getId());
                    dealBo.setReturnStatus("0");
                    dealBo.setContacts(taskBo.getName());
                    dealBo.setItems(ddtls);
                    exWarehouseService.insertByBo(dealBo);
                } else {
                    BeanUtil.copyProperties(dealVo, dealBo);
                    dealBo.setNums(taskBo.getNums());
                    dealBo.setStoreId(taskBo.getStoreId());
                    exWarehouseService.updateByBo(dealBo);
                }

                commonService.saveOperatorLog(taskBo.getId(), "oms", "下发");
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean handoverSave(HandoverBo bo) {

        TaskVo oldTask = taskService.queryById(bo.getObjid());
        TaskBo taskBo = new TaskBo();
        BeanUtil.copyProperties(oldTask, taskBo);
        taskBo.setStatus("1");//更新为已完成
        if (!taskService.updateByBoV2(taskBo)) {
            throw new RuntimeException("更新任务状态失败");
        }
        if (handoverService.insertByBo(bo) == null) {
            throw new RuntimeException("保存交接信息失败");
        }
        if (!handoverService.updateByBo(bo)) {
            throw new RuntimeException("更新交接信息失败");
        }

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void disposalApply(TaskDisposalApplyBo bo) {

        bo.getTaskInfo().setType("2");
        bo.getTaskInfo().setStatus(Constants.DEFAULT_STATUS);
        bo.getTaskInfo().setDelFlag(Constants.DEFAULT_STATUS);
        bo.getTaskInfo().setTaskNo(getNo("C"));//设置编号
        bo.getTaskInfo().setSendStatus(Constants.DEFAULT_STATUS);
        bo.getTaskInfo().setSendReStatus(Constants.DEFAULT_STATUS);
        bo.getTaskInfo().setCheckStatus(Constants.DEFAULT_STATUS);

        //proInfo total number
        long proTotalNumber =
                bo.getProList().stream().map(TaskDtlVo::getNums).mapToLong(Long::valueOf).sum();

        bo.getTaskInfo().setNums(proTotalNumber);

        //inset task info
        if (baseMapper.insert(bo.getTaskInfo()) == 0) {
            throw new RuntimeException("保存任务信息失败");
        }

        // update oss info of disposal list
        sysOssMapper.updateBatchBussAndObjIdById(bo.getDisposalInfo().getDisposalListOss(),
                OssBuss.DISPOSAL_APPLY_LIST, bo.getTaskInfo().getId());

        // update oss info of authorization
        sysOssMapper.updateBatchBussAndObjIdById(bo.getDisposalInfo().getAuthorizationOss(),
                OssBuss.DISPOSAL_APPLY_AUTHORIZE, bo.getTaskInfo().getId());

        // update oss info of authorization
        sysOssMapper.updateBatchBussAndObjIdById(bo.getDisposalInfo().getCertNoPhotoOss(),
                OssBuss.DISPOSAL_APPLY_CERT, bo.getTaskInfo().getId());

        commonService.saveOperatorLog(bo.getTaskInfo().getId(), "oms", PropertyLogType.DISPOSAL_TASK.getInfo());//操作日志

        if (taskDisposalInfoMapper.insert(bo.getDisposalInfo()) == 0) {
            throw new RuntimeException("保存处置申请信息失败");
        }

        // ignore properties of taskDtl entity copy property entity
        String[] ignoreProperties = {"id", "nums", "createBy", "createTime", "updateBy", "updateTime"};

        //get  property no  of task
        List<TaskDtl> taskDtls = bo.getProList().stream().map(proInfo -> {

            Property property = propertyMapper.selectPropertyByPno(proInfo.getPno());
            TaskDtl taskDtl = new TaskDtl();
            BeanUtil.copyProperties(property, taskDtl, ignoreProperties);
            taskDtl.setTaskId(bo.getTaskInfo().getId());
            taskDtl.setNums(proInfo.getNums());
            taskDtl.setDealType(String.valueOf(bo.getDisposalInfo().getDisposalType()));
            taskDtl.setDelFlag(Constants.DEFAULT_STATUS);
            taskDtl.setStatus(Constants.DEFAULT_STATUS);
            String info = JsonUtils.toJsonString(taskDtl);
            String logContent =
                    PropertyLogType.DISPOSAL_TASK.getInfo() + "：(物品编号：" + taskDtl.getPno() + "，物品名称：" + taskDtl.getName() + "，申请说明：" + (StringUtils.isNotEmpty(bo.getTaskInfo().getRemark()) ? bo.getTaskInfo().getRemark() : "") + ")";
            commonService.savePropertyLog(taskDtl.getPno(), bo.getTaskInfo().getId(), taskDtl.getName(),
                    PropertyLogType.DISPOSAL_TASK.getCode(), logContent, taskDtl.getDeptId(), info,
                    bo.getTaskInfo().getStoreId(), taskDtl.getNums(), null);

            return taskDtl;
        }).collect(Collectors.toList());


        if (!taskDtlMapper.insertBatch(taskDtls)) {
            throw new RuntimeException("保存任务财物失败");
        }

        //sms notice
        String phone = configService.selectConfigByKey("app.oms.dispatch.phone");
        SmsRequest smsRequest = new SmsRequest();
        smsRequest.setTemplateCode(SmsTemplateCode.DISPOSAL_NOTICE.getSMS_CODE());
        smsRequest.setPhoneNumber(phone);
        SmsTemplateParam templateParam = new SmsTemplateParam();
        templateParam.setArea(deptMapper.getAreaName(LoginHelper.getDeptId()));
        smsRequest.setTemplateParam(templateParam);
        aliyunSmsService.AliyunSmsSend(smsRequest);

        String dealPhone = configService.selectConfigByKey("app.oms.deal.phone");
        if (!StringUtils.isEmpty(dealPhone)) {
            smsRequest.setPhoneNumber(dealPhone);
            aliyunSmsService.AliyunSmsSend(smsRequest);
        }

    }

    @Override
    public void disposalUpdate(TaskDisposalApplyBo bo) {

        long proTotalNumber =
                bo.getProList().stream().map(TaskDtlVo::getNums).mapToLong(Long::valueOf).sum();

        bo.getTaskInfo().setNums(proTotalNumber);

        if (baseMapper.updateById(bo.getTaskInfo()) == 0) {
            throw new RuntimeException("保存任务信息失败");
        }

        sysOssMapper.updateBatchBussAndObjIdById(bo.getDisposalInfo().getDisposalListOss(),
                OssBuss.DISPOSAL_APPLY_LIST, bo.getTaskInfo().getId());

        sysOssMapper.updateBatchBussAndObjIdById(bo.getDisposalInfo().getAuthorizationOss(),
                OssBuss.DISPOSAL_APPLY_AUTHORIZE, bo.getTaskInfo().getId());

        sysOssMapper.updateBatchBussAndObjIdById(bo.getDisposalInfo().getCertNoPhotoOss(),
                OssBuss.DISPOSAL_APPLY_CERT, bo.getTaskInfo().getId());

        if (taskDisposalInfoMapper.updateById(bo.getDisposalInfo()) == 0) {
            throw new RuntimeException("保存处置申请信息失败");
        }

        String[] ignoreProperties = {"id", "nums", "createBy", "createTime", "updateBy", "updateTime"};

        /**
         * 查询原明细数据
         */
        TaskDtlBo dtlBo = new TaskDtlBo();
        dtlBo.setTaskId(bo.getTaskInfo().getId());
        dtlBo.setDelFlag(Constants.DEFAULT_STATUS);
        List<TaskDtlVo> olds = taskDtlMapper.selectTaskDtlList(dtlBo);

        List<TaskDtl> taskDtls = bo.getProList().stream().map(proInfo -> {
            TaskDtl taskDtl = new TaskDtl();
            if (proInfo.getTaskId() == null) {
                Property property = propertyMapper.selectPropertyByPno(proInfo.getPno());
                BeanUtil.copyProperties(property, taskDtl, ignoreProperties);
                taskDtl.setTaskId(bo.getTaskInfo().getId());
                taskDtl.setDelFlag(Constants.DEFAULT_STATUS);
                taskDtl.setStatus(Constants.DEFAULT_STATUS);
                String info = JsonUtils.toJsonString(taskDtl);
                String logContent =
                        PropertyLogType.DISPOSAL_TASK.getInfo() + "：(物品编号：" + taskDtl.getPno() + "，物品名称：" + taskDtl.getName() + "，申请说明：" + (StringUtils.isNotEmpty(bo.getTaskInfo().getRemark()) ? bo.getTaskInfo().getRemark() : "") + ")";
                commonService.savePropertyLog(taskDtl.getPno(), bo.getTaskInfo().getId(), taskDtl.getName(),
                        PropertyLogType.DISPOSAL_TASK.getCode(), logContent, taskDtl.getDeptId(), info,
                        bo.getTaskInfo().getStoreId(), taskDtl.getNums(), null);

            } else {
                taskDtl.setId(proInfo.getId());

            }
            taskDtl.setNums(proInfo.getNums());
            taskDtl.setDealType(String.valueOf(bo.getDisposalInfo().getDisposalType()));

            return taskDtl;
        }).collect(Collectors.toList());


        if (!taskDtlMapper.insertOrUpdateBatch(taskDtls)) {
            throw new RuntimeException("保存任务财物失败");
        }

        List<String> ids = bo.getProList().stream().map(TaskDtlVo::getId).collect(Collectors.toList());

        olds.forEach(old -> {
            if (!ids.contains(old.getId())) {
                taskDtlMapper.deleteByDtlId(old.getId());
            }
        });
    }

    private QueryWrapper<Object> getDisposalNotRegisterQueryBuild(DisposalNotRegisterBo bo) {

        return new QueryWrapper<>().func(i -> {
            i.eq(StrUtil.isNotBlank(bo.getRegion()), "DP.REGION", bo.getRegion());
            i.eq(StrUtil.isNotBlank(bo.getTaskNo()), "T.TASK_NO", bo.getTaskNo());
            i.like(StrUtil.isNotBlank(bo.getProNo()), "TD.PNO", bo.getProNo());
            i.eq(StrUtil.isNotBlank(bo.getDisposalType()), "TDI.DISPOSAL_TYPE", bo.getDisposalType());
            i.eq(StrUtil.isNotBlank(bo.getAuthCenter()), "TDI.AUTH_CENTER", bo.getAuthCenter());
            i.eq("0".equals(bo.getAuthCenter()), "T.DEPT_ID", LoginHelper.getDeptId());
            i.eq(bo.getInCenter() != null && bo.getInCenter() == 1, "t.source", 0);
            i.eq(bo.getInCenter() != null && bo.getInCenter() == 0, "t.source", 1);
        });
    }

    @Override
    public List<RegionOverviewVo> getDisposalNotRegisterOverview() {

        return baseMapper.getDisposalNotRegisterOverview();
    }

    @Override
    public TableDataInfo<DisposalNotRegisterBo> getDisposalNotRegisterPage(DisposalNotRegisterBo bo, PageQuery pageQuery) {

        return TableDataInfo.build(baseMapper.getDisposalNotRegisterList(pageQuery.build(),
                getDisposalNotRegisterQueryBuild(bo)));
    }

    @Override
    public List<DisposalNotRegisterBo> getDisposalNotRegisterList(DisposalNotRegisterBo bo) {

        return baseMapper.getDisposalNotRegisterList(getDisposalNotRegisterQueryBuild(bo));
    }

    @Override
    public List<AuthCenterDisposalBo> getAuthCenterDisposalList() {

        List<AuthCenterDisposalBo> authCenterDisposalList = taskDisposalInfoMapper.getAuthCenterDisposalList();
        authCenterDisposalList.add(new AuthCenterDisposalBo(authCenterDisposalList));
        return authCenterDisposalList;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(com.xmtlxx.oms.domain.Task entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    public String getNo(String num) {
//        LambdaQueryWrapper<Task> lqw = Wrappers.lambdaQuery();
//        Long maxNumObject = baseMapper.selectCount(lqw);
        Long maxNumObject = baseMapper.selectCountAlls();
//        String num = "";
        String todayStr = DateUtils.date2String(new Date(), "yyMMdd");

        if (maxNumObject == null) {
            num += todayStr + "000001";
        } else {
            String maxnumStr = "00000" + maxNumObject.toString();
            String maxnumNo = maxnumStr.substring(maxnumStr.length() - 6, maxnumStr.length());
            String nextnumNo = StringUtils.nextNo(maxnumNo, 6);
            num += todayStr + nextnumNo;
        }
        return num;
    }


    @Override
    public DisposalProVo getDisposalProInfo(String pno) {

        return baseMapper.getDisposalProInfo(pno);
    }

    @Override
    public Page<DisposalTempStorageBo> getTempStorageList(PageQuery pageQuery, DisposalTempStorageBo bo) {

        return baseMapper.getTempStorageList(pageQuery.build(), bo);
    }

    @Override
    public List<DisposalTempStorageBo> getTempStorageListExport(DisposalTempStorageBo bo) {

        return baseMapper.getTempStorageList(bo);
    }

    @Override
    public TaskVo getTaskById(String id) {

        TaskVo taskById = taskService.getTaskById(id);

        taskById.setDisposalInfo(taskDisposalInfoMapper.getDisposalInfo(id));

        SysOssBo ossBo = new SysOssBo();
        ossBo.setObjid(id);
        ossBo.setBuss(OssBuss.DISPOSAL_APPLY_LIST.getValue());
        taskById.getDisposalInfo().setDisposalListOss(sysOssMapper.selectOssList(ossBo));

        ossBo.setBuss(OssBuss.DISPOSAL_APPLY_AUTHORIZE.getValue());
        taskById.getDisposalInfo().setAuthorizationOss(sysOssMapper.selectOssList(ossBo));

        ossBo.setBuss(OssBuss.DISPOSAL_APPLY_CERT.getValue());
        taskById.getDisposalInfo().setCertNoPhotoOss(sysOssMapper.selectOssList(ossBo));
        return taskById;
    }

}
